<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img :src="avatar" class="preview" v-if="avatar"/>
      <img src="../../../assets/images/avatar.jpg" class="preview" alt="" v-else />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input type="file" accept="image/*" style="display: none;" ref="iptRef" @change="onChange"/>
        <el-button type="primary" icon="el-icon-plus" @click="chooseImage">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" :disabled="avatar?false:true" @click="clickUpload">上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data () {
    return {
      avatar: ''
    }
  },
  methods: {
    chooseImage () {
      this.$refs.iptRef.click()
    },
    onChange (e) {
      if (e.target.files.length === 0) {
        //   没有选择图征
      } else {
        //   选择了图片
        // 需求: 实现图片的预览, 上传到服务器了吗?
        // 条件:有图片对象   结果: 图片的base64的字符串
        // 1.创建文件读取器的实例
        const reader = new FileReader()
        // 2.调用方法读取文件对象 (异步)
        reader.readAsDataURL(e.target.files[0])
        // 3.读取成功事件
        reader.onload = () => {
          // 读取成功的数据放在 实例.result
        //   console.log(reader.result)
          this.avatar = reader.result
        }
      }
    },
    async clickUpload () {
      // post put patch   axios.post(地址,{})
      // get delete       axios.get(地址,{params:{数据}})
      const { data: res } = await this.$http.patch('/my/update/avatar', { avatar: this.avatar })
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)

      // 重新获取用户信息
      this.$store.dispatch('initUserInfo')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  width: 400px;
  height: 300px;
  object-fit: cover;
}
</style>
